package com.yafeed.trade.common.http;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @program:
 * @description:
 * @author: yanghj
 * @time: 2020-12-13 01:34
 */

@Component
public class HttpUtils {

    private RestTemplate restTemplate;


    /**
     * <pre>
     *     向目的URL发送 http 请求
     * </pre>
     *
     * @param url        请求地址
     * @param method     请求类型
     * @param httpEntity 请求实体
     * @param clazz      序列化类型
     * @param <T>        序列化类型
     * @return <T>
     */
    private <T> T http(String url, HttpMethod method, @Nullable HttpEntity<Map<String, Object>> httpEntity, Class<T> clazz) {
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<T> response = restTemplate.exchange(url, method, httpEntity, clazz);
        return response.getBody();
    }


    /**
     * 向目的URL发送post请求
     *
     * @param url   目的url
     * @param clazz 序列化类型
     * @param <T>   T
     * @return T
     */
    public <T> T get(String url, Class<T> clazz) {
        return http(url, HttpMethod.GET, null, clazz);
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

}
